package com.cloudRestudy.gateway.filter;
import com.alibaba.fastjson.JSONObject;
import com.cloudRestudy.common.core.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @ClassName : GlobalLogFilter
 * @Author : lby
 * @Date: 2021/7/31 16:53
 * @Description : 全局log 过滤器
 */
@Component
@Slf4j
public class GlobalLogFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        // 请求地址
        String path = request.getPath().toString();
        // 请求参数
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        // 请求类型
        String method = request.getMethod().toString();
        // 请求过滤拦截
        if (queryParams.isEmpty()) {
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            log.error("请求错误:{}","参数异常");
            return this.getMsg("参数异常", response);
        }
        return chain.filter(exchange);
    }


    /**
     * 过滤器加载顺序，越小优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }


    /**
     * response 设置返回数据
     * @param msg
     * @param response
     * @return
     */
    public Mono<Void> getMsg(String msg,ServerHttpResponse response){
        msg = new String(msg.getBytes(StandardCharsets.UTF_8),StandardCharsets.UTF_8);
        byte[] bytes = JSONObject.toJSONString(R.failed(msg)).getBytes(StandardCharsets.UTF_8);
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        response.getHeaders().add("Content-type","text/html;charset=UTF-8");
        Mono<Void> voidMono = response.writeWith(Flux.just(wrap));
        return voidMono;
    }
}
